<?php

namespace app\api\model\coupon;

use think\Model;


class Coupon extends Model
{





    // 表名
    protected $name = 'coupon';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'coupon_type_module_text',
        'end_use_time_text'
    ];




    public function getCouponTypeModuleList()
    {
        return ['service' =>'服务人员优惠券(服务人员承兑)','house'=>'业主优惠券(业主承兑)','general'=>'平台通用优惠券(平台承兑)'];
    }

    public function getCouponTypeModuleTextAttr($value, $data)
    {
        $value = $value ?: ($data['module'] ?? '');
        $list = $this->getCouponTypeModuleList();
        return $list[$value] ?? '';
    }


    public function getEndUseTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['end_use_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    /*protected function setEndUseTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }*/


    public function useCoupon($coupon_id, $user_id, $use_order_id)
    {
        $data      = array('use_order_id' => $use_order_id, 'use_time' => time(), 'state' => 2);

        $res = Coupon::update($data,['coupon_id'=>$coupon_id,'user_id'=>$user_id,'state'=>1]);

        return $res;
    }

    public function refundCoupon($coupon_id, $user_id)
    {
        $result = Coupon::where(['coupon_id'=>$coupon_id,'user_id'=>$user_id,'state' => 2])->update(['use_time' => 0, 'state' => 1]);
        return $result;
    }

}
